
//
//  GPContactController.m
//  Keping
//
//  Created by 23 on 2017/12/7.
//  Copyright © 2017年 柯平. All rights reserved.
//
// 联系人页面


#import "GPContactController.h"
#import "GPContactRequest.h"
#import "GPContactListModel.h"
#import "GPContactCell.h"
#import "GPContactHeaderView.h"
#import "GPChatController.h"
#import "GPFriendRequestController.h"
#import "GPLongPressMenuController.h"
#import "GPUserProfileController.h"
#import "GPUserProfileController.h"
#import "GPSearchContanctController.h"
#import "GPVideoCallManager.h"

@interface GPContactController () <UITableViewDataSource, UITableViewDelegate, GPLongPressMenuControllerDelegate>

/**搜索按钮*/
@property(nonatomic,weak) UIButton *searchButton;
/**tableView*/
@property(nonatomic,weak) UITableView *tableView;

/**bookViews*/
@property(nonatomic,strong) NSMutableArray *bookViews;
/**communityViews*/
@property(nonatomic,strong) NSMutableArray *communityViews;
/**friendViews*/
@property(nonatomic,strong) NSMutableArray *friendViews;

/**bookView是否展开*/
@property(nonatomic,assign) BOOL isBookViewsOpen;
/**comunityView是否展开*/
@property(nonatomic,assign) BOOL isCommunityViewsOpen;
/**friendView是否展开*/
@property(nonatomic,assign) BOOL isFriendViewsOpen;

/**社区名称*/
@property(nonatomic, copy) NSString *commName;

@end

@implementation GPContactController

static NSString * const Id = @"contact";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //设置UI
    [self setupUI];
    
    //加载数据
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadData];
}

#pragma mark - 设置UI
/**设置UI*/
- (void)setupUI
{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setTitle:@"Search" forState:UIControlStateNormal];
    [searchButton setImage:[UIImage imageNamed:@"search_icon"] forState:UIControlStateNormal];
    [searchButton setTitleColor:COLOR(56, 87, 242) forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [searchButton addTarget:self action:@selector(searchBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchButton];
    self.searchButton = searchButton;
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 75.f;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass(GPContactCell.class) bundle:nil] forCellReuseIdentifier:Id];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    [searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(self.view).offset(10);
        make.right.mas_equalTo(self.view).offset(-10);
        make.height.mas_equalTo(44);
    }];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(searchButton.mas_bottom).offset(10);
    }];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    self.searchButton.layer.cornerRadius = 22;
    self.searchButton.layer.masksToBounds = YES;
    self.searchButton.layer.borderWidth = 1.0;
    self.searchButton.layer.borderColor = [COLOR(56, 87, 242) CGColor];
    
}

#pragma mark - UITableViewDataSouce, UITableViewDelegate

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        // phonebook  9
        return self.isBookViewsOpen?self.bookViews.count:0;
    }else if(section == 1){
        // smart community 1
        return self.isCommunityViewsOpen?self.communityViews.count:0;
    }else if (section == 0){
        // firends 5
        return self.isFriendViewsOpen?self.friendViews.count:0;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPContactCell *cell = [tableView dequeueReusableCellWithIdentifier:Id];
    cell.type = GPContactCellTypeContact;
    GPContactModel *contact = nil;
    
    if (indexPath.section == 2) {
        contact =  self.bookViews[indexPath.row];
    }else if(indexPath.section == 1){
        contact =  self.communityViews[indexPath.row];
    }else if (indexPath.section == 0){
        contact =  self.friendViews[indexPath.row];
    }
    
    cell.contact = contact;
    
    WEAKSELF
    //添加好友
    cell.callback = ^(GPContactModel *contactModel) {
      
        //添加好友
        GPFriendRequestController *vc = [[GPFriendRequestController alloc] init];
        vc.friendId = contact.partyId;
        vc.nickname = contact.nickName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    };
    
    //长按
    cell.longPressCallback = ^(GPContactModel *contactModel) {
      
        if (indexPath.section != 0){
            return ;
        }
        
        GPLongPressMenuController *vc = [[GPLongPressMenuController alloc] init];
        vc.contact = contact;
        vc.delegate = weakSelf;
        [weakSelf presentViewController:vc animated:NO completion:nil];
        
    };
    
    //接受好友的请求
    cell.acceptCallback = ^(GPContactModel *contactModel) {
      
        //
        [self acceptFriendRequest:contactModel];
        
        
    };
    
    return cell;
}

//统一好友请求
- (void)acceptFriendRequest:(GPContactModel *)contactModel
{
    GPContactRequest *request = [[GPContactRequest alloc] initWithURL:kIMAcceptFriendRequestURL];
    request.isPost = YES;
    request.params = @{@"id":contactModel.partyId};
    
    [self showLoading];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        
        NSDictionary *response = request.responseJSONObject;
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        [self showSuccess:@"success"];
        
        [self loadData];
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
    }];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    GPContactHeaderView *headerView = [GPContactHeaderView headerView];
    WEAKSELF
    
    //设置UI
    if (section == 2) {
        
        headerView.nameLabel.text = @"Phonebook";
        headerView.numberLabel.text = [NSString stringWithFormat:@"%zd", self.bookViews.count];
        headerView.indicatorView.selected = self.isBookViewsOpen;
        headerView.callback = ^() {
            weakSelf.isBookViewsOpen = !weakSelf.isBookViewsOpen;
            [weakSelf.tableView reloadSection:section withRowAnimation:UITableViewRowAnimationNone];
        };
        
    }else if(section == 1){
        
//        headerView.nameLabel.text = @"Setia path community";
        headerView.nameLabel.text = self.commName;
        headerView.numberLabel.text = [NSString stringWithFormat:@"%zd", self.communityViews.count];
        headerView.indicatorView.selected = self.isCommunityViewsOpen;
        headerView.callback = ^() {
            weakSelf.isCommunityViewsOpen = !weakSelf.isCommunityViewsOpen;
            [weakSelf.tableView reloadSection:section withRowAnimation:UITableViewRowAnimationNone];
        };
        
    }else if (section == 0){
        
        headerView.nameLabel.text = @"My Friends";
        headerView.numberLabel.text = [NSString stringWithFormat:@"%zd", self.friendViews.count];
        headerView.indicatorView.selected = self.isFriendViewsOpen;
        headerView.callback = ^() {
            weakSelf.isFriendViewsOpen = !weakSelf.isFriendViewsOpen;
            [weakSelf.tableView reloadSection:section withRowAnimation:UITableViewRowAnimationNone];
        };
        
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GPContactModel *contact = nil;
    
    if (indexPath.section == 2) {
        contact =  self.bookViews[indexPath.row];
        return;
    }else if(indexPath.section == 1){
        contact =  self.communityViews[indexPath.row];
        if (contact.status != 2) {
            return;
        }
    }else if (indexPath.section == 0){
        contact =  self.friendViews[indexPath.row];
        //只有好友的才可以跳转到聊天
    }
    
    
    GPChatViewModel *chatViewModel = [[GPChatViewModel alloc] initWithChatType:EMChatTypeChat conversationId:contact.phone toId:contact.phone toNickName:contact.nickName toAvatarURLPath:[KGetImageURL stringByAppendingPathComponent:contact.profile]];
    chatViewModel.uid = contact.partyId;
    if (self.isShare) {
        [chatViewModel sendSOSTestMessage:self.shareText];
    }
    GPChatController *vc = [[GPChatController alloc] init];
    vc.chatViewModel = chatViewModel;
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - 加载数据
- (void)loadData
{
    [self showLoading];
    GPContactRequest *request = [[GPContactRequest alloc] initWithURL:kIMGetContactListPath];
    [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        [self hideHUD];
        
        NSDictionary *response = request.responseJSONObject;
        
        if ([response[@"statusCode"] integerValue] != 200) {
            
            [self showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            return;
        }
        
        NSArray *items = response[@"items"];
        if (items.count >= 2) {
            self.commName = items[1];
        }else{
            self.commName = @"接口未返回";
        }
        NSArray *friendViewsDict = response[@"friendViews"];
        NSArray *communityViewsDict = response[@"communityViews"];
        NSArray *bookViewsDict = response[@"bookViews"];
        
        NSMutableArray *arrayM_1 = [NSMutableArray array];
        for (NSDictionary *friend in friendViewsDict) {
            GPContactModel *model = [GPContactModel modelWithDictionary:friend];
            [arrayM_1 addObject:model];
        }
        
        NSMutableArray *arrayM_2 = [NSMutableArray array];
        for (NSDictionary *comuity in communityViewsDict) {
            GPContactModel *model = [GPContactModel modelWithDictionary:comuity];
            [arrayM_2 addObject:model];
        }
        
        NSMutableArray *arrayM_3 = [NSMutableArray array];
        for (NSDictionary *book in bookViewsDict) {
            GPContactModel *model = [GPContactModel modelWithDictionary:book];
            [arrayM_3 addObject:model];
        }
        
        self.friendViews = [NSMutableArray arrayWithArray:arrayM_1];
        self.communityViews = [NSMutableArray arrayWithArray:arrayM_2];
        self.bookViews =  [NSMutableArray arrayWithArray:arrayM_3];
        
        //刷新表格
        [self.tableView reloadData];
        
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        
    }];
}

#pragma mark - action
//点击搜索
- (void)searchBtnDidClick
{
    GPSearchContanctController *vc = [[GPSearchContanctController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - GPLongPressMenuControllerDelegate

- (void)menuType:(GPLongPressMenuType)type didItemClicked:(GPContactModel *)contact
{
    switch (type) {
        case GPLongPressMenuTypeProfile:
        {
            //查看详情
            GPUserProfileController *vc = [[GPUserProfileController alloc] init];
            vc.uid = contact.partyId;
            vc.phone = contact.phone;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case GPLongPressMenuTypeVoice:
        {
            [[GPVideoCallManager shareManager] startCall:EMCallTypeVoice username:contact.phone ext:nil];
        }
            break;
        case GPLongPressMenuTypeVideo:
        {
            [[GPVideoCallManager shareManager] startCall:EMCallTypeVideo username:contact.phone ext:nil];
        }
            break;
        case GPLongPressMenuTypePhone:
        {
            NSString *phone = [NSString stringWithFormat:@"%@%@",contact.prix, contact.phone];
            NSString *urlStr = [NSString stringWithFormat:@"tel://%@", phone];
            NSURL *url = [NSURL URLWithString:urlStr];
            if([[UIApplication sharedApplication] canOpenURL:url]){
                [[UIApplication sharedApplication] openURL:url];
            }
        }
            break;
        case GPLongPressMenuTypeBlock:
        {
            //加入黑名单
            WEAKSELF
            //加入黑名
            UIAlertController *vc = [UIAlertController alertControllerWithTitle:nil message:@"Are you sure you want to unblock this contact?" preferredStyle:UIAlertControllerStyleAlert];
            [vc addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
                GPUserProfileController *vc = [[GPUserProfileController alloc] init];
                vc.uid = contact.partyId;
                vc.phone = contact.phone;
                [vc blockUser:YES completion:^(BOOL success) {
                    if (success) {
                        [weakSelf showSuccess:@"success"];
                    }else{
                        [weakSelf showErrorText:@"failture"];
                    }
                }];
                
            }]];
            [vc addAction:[UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:vc animated:YES completion:nil];
            
        }
            break;
            
        default:
            break;
    }
}


#pragma mark - lazy

- (NSMutableArray *)friendViews
{
    if (_friendViews == nil) {
        _friendViews = [NSMutableArray array];
    }
    return _friendViews;
}

- (NSMutableArray *)bookViews
{
    if (_bookViews == nil) {
        _bookViews = [NSMutableArray array];
    }
    return _bookViews;
}

- (NSMutableArray *)communityViews
{
    if (_communityViews == nil) {
        _communityViews = [NSMutableArray array];
    }
    return _communityViews;
}

@end


















